local event = require("event")

local function checkButtonPress(self,x,y)
	if x >= self.x and x < self.x+self.w
		and y >= self.y and y < self.y+self.h then
		return true
	end
	return false
end

local function resetButton(self)
	self.state = false
end

local function processButton(self,x,y)
	if checkButtonPress(self,x,y) then
		if self.callback ~= nil then self:callback() end
		if self.timeout == nil then self.timeout = 0 end
		if self.timeout > 0 and not self.state then
			self.state = true
			event.timer(self.timeout,function() self:reset() end)
		elseif self.timeout == 0 then
			self.state = not self.state
		end
	end
end

local function getButtonState(self)
	return self.state
end

local function createButton(x,y,w,h,timeout,callback,id)
	return {
		x = x,
		y = y,
		w = w,
		h = h,
		state = false,
		timeout = timeout,
		press = processButton,
		get = getButtonState,
		reset = resetButton,
		callback = callback,
		id = id
	}
end

return {
	create = createButton
}
